package XaSqlStudy;

import com.mysql.cj.jdbc.MysqlXADataSource;

import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.sql.Connection;
import java.sql.Statement;

public class XADemo {
    public static MysqlXADataSource GetDataSource(String commString,String user,String passwd){
        try{
            MysqlXADataSource ds=new MysqlXADataSource();
            ds.setUrl(commString);
            ds.setUser(user);
            ds.setPassword(passwd);
            return ds;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        //数据库1地址
        String connString1="jdbc:mysql://localhost:3306/employees";
        //数据库2地址
        String connString2="jdbc:mysql://localhost:3306/peixun";
        try{
            //创建资源管理器1
            MysqlXADataSource ds1=GetDataSource(connString1,"root","yanjiadou");
            //创建资源管理器2
            MysqlXADataSource ds2=GetDataSource(connString2,"root","yanjiadou");

            //获得资源管理器1的连接
            XAConnection xaConnection1=ds1.getXAConnection();
            XAResource xaResource1=xaConnection1.getXAResource();
            Connection connection1=xaConnection1.getConnection();
            Statement statement1=connection1.createStatement();
            //获得资源管理器2的连接
            XAConnection xaConnection2=ds2.getXAConnection();
            XAResource xaResource2=xaConnection2.getXAResource();
            Connection connection2=xaConnection2.getConnection();
            Statement statement2=connection2.createStatement();

            //创建资源管理器1的唯一标识
            Xid xid1=new MyXid(100,new byte[]{0x01},new byte[]{0x02});
            //创建资源管理器2的唯一标识
            Xid xid2=new MyXid(100,new byte[]{0x11},new byte[]{0x12});

            try{
              xaResource1.start(xid1,XAResource.TMNOFLAGS);
              int num1=statement1.executeUpdate("update accountBank set money=money-10000 where userid=1");
              xaResource1.end(xid1,XAResource.TMSUCCESS);

              xaResource2.start(xid2,XAResource.TMNOFLAGS);
              int num2=statement2.executeUpdate("update accountBank set money=money+10000 where userid=2");
              xaResource2.end(xid2,XAResource.TMSUCCESS);
              if(num1==1&&num2==1){
                  //资源管理器1第一阶段准备
                  int ret1=xaResource1.prepare(xid1);
                  //资源管理器2第一阶段准备
                  int ret2=xaResource2.prepare(xid2);
                  //事务管理器提交
                  if(ret1 == XAResource.XA_OK&&ret2 == XAResource.XA_OK){
                      xaResource1.commit(xid1,false);
                      xaResource2.commit(xid2,false);
                  }
              }
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
